package com.matrix.draft.astigautoconfigure;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * 该自动配置的功能是自动配置一个Redis-stater
 */
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties(AstigProperties.class)
@ConditionalOnClass({RedisOperations.class}) // 因为我这个自动配置需要需要依赖Redis
public class AstigAutoConfiguration {

    @Bean
    JedisConnectionFactory jedisConnectionFactory(AstigProperties properties) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(
                new RedisStandaloneConfiguration(properties.getHost(), properties.getPort())
        );
        return jedisConnectionFactory;
    }

    @Bean
    RedisTemplate<Object, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        // 准备RedisTemplate
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        // 设置序列化方式
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.java());
        System.err.println("RedisTemplate<Object,Object> is registered");
        return redisTemplate;
    }

    // 随便配置一个Bean试试
    @Bean
    String paintedEggshell() {
        System.err.println("painted eggshell is already registered");
        return "Hello, I am astig! This is a painted eggshell";
    }
}
